package com.easyjob.config;

import com.easyjob.entity.config.AppConfig;
import com.easyjob.entity.constants.Constants;
import com.easyjob.entity.dto.AppUserLoginDto;
import com.easyjob.utils.JWTUtil;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author Const
 */
public class AuthInterceptor implements HandshakeInterceptor {

    @Resource
    private JWTUtil<AppUserLoginDto> jwtUtil;

    @Resource
    private AppConfig appConfig;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String token = ((ServletServerHttpRequest) request).getServletRequest().getParameter("token");
        AppUserLoginDto loginDto = null;
        try {
            loginDto = jwtUtil.getTokenData(Constants.JWT_KEY_LOGIN_TOKEN, token, AppUserLoginDto.class);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        attributes.put("userId", loginDto.getUserId());
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
